package com.itlong.cloud.iot.alibaba.mns.polling;

import com.aliyun.mns.client.CloudAccount;
import com.aliyun.mns.client.MNSClient;
import com.aliyun.mns.model.Message;
import com.itlong.cloud.POJO.DTO.property.IotCloudIntercomStateDTO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.iot.alibaba.util.AliClient;
import com.itlong.cloud.iot.alibaba.mns.CloudQueueMessageReceiver;
import com.itlong.cloud.commons.dao.IDeviceEntranceInfoDao;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.rabbitmq.config.MessageSender;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.utils.node.JsonUtil;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <desc>
 *      Iot云对讲实时获取设备状态轮询类
 * </desc>
 *
 * @createDate 2019/07/16
 */
@Service
@RefreshScope
public class IotCloudIntercomDeviceStatePolling {
    private static final Logger LOG = LoggerFactory.getLogger(IotCloudIntercomDeviceStatePolling.class);
    protected static MNSClient sMNSClient;
    @Autowired
    RedisService redisService;
    @Autowired
    MessageSender messageSender;
    @Autowired
    AliClient aliClient;
    @Value("${" + PlatformConstants.MNSEndpoint + "}")
    private  String endpoint;    //消息服务Endpoint
    @Value("${" + PlatformConstants.CLOUD_INTERCOM_DEVICE_STATE_QUEUE + "}")
    private  String QueueName;  //队列名
    private ExecutorService cachedThreadPool ; //线程池

    @Autowired
    IDeviceEntranceInfoDao iDeviceEntranceInfoDao;

    /**
     * <desc>
     *      线程开始轮询
     * </desc>
     *
     * @param workerId
     * @author Qiang.S
     * @createDate 2019/07/16
     */
    public void worker(int workerId) {
        CloudQueueMessageReceiver receiver = new CloudQueueMessageReceiver(workerId, sMNSClient, QueueName);
        while (true) {
            Message message = receiver.receiveMessage();
            //读取到设备上传的状态数据，并设置缓存
            try {
                LOG.info(String.format("【获取云对讲设备状态】：%s",message.getMessageBodyAsBase64()));
                IotCloudIntercomStateDTO dto = JsonUtil.toObject(message.getMessageBodyAsBase64(), IotCloudIntercomStateDTO.class);
                //设置缓存
                redisService.set(RedisConstant.REDIS_IOT_CLOUD_INTERCOM_STATE_CACHE +dto.getDeviceName() + "_" + message.getFirstDequeueTime().getTime(),
                        RedisConstant.REDIS_IOT_CLOUD_INTERCOM_STATE_CACHE_TIME, dto);
            } catch (Exception e) {
                LOG.error("【MNS获取云对讲设备数据异常】" + e.getMessage());
                e.printStackTrace();
            } finally {
                //处理完后删除队列消息
                sMNSClient.getQueueRef(QueueName).deleteMessage(message.getReceiptHandle());
            }
        }
    }

    /**
     * <desc>
     *      初始化
     * </desc>
     *
     * @author Qiang.S
     * @createDate 2019/07/16
     */
    @PostConstruct
    public void polling(){
        //初始化线程池
        cachedThreadPool = Executors.newFixedThreadPool(10);
        CloudAccount account = aliClient.getCloudAccount(endpoint);
        sMNSClient = account.getMNSClient();
        //开启10个线程读取消息
        for(int i=1;i<=10;i++){
            int id=i;
            cachedThreadPool.execute(() -> {
                worker(id);
            });
        }
    }
}
